package redis.clients.jedis.util;

import java.io.Closeable;
import java.util.NoSuchElementException;

import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.exceptions.JedisException;
import redis.clients.jedis.exceptions.JedisExhaustedPoolException;


/**
 * Jedis Pool是Redis的Java客户端Jedis提供的一个连接池实现。
 * 它允许你创建和管理一个Jedis实例的池子，以提高应用程序的性能和可扩展性。
 *
 * 1、减少创建和销毁Jedis实例的开销，提高应用程序性能。
 * 2、复用已创建的Jedis实例，避免频繁地创建和销毁对象，降低内存消耗。
 * 3、支持自动管理Jedis实例的数量，根据需要动态调整连接数。
 * 4、支持Jedis实例的负载均衡，将请求分发到不同的Jedis实例上。
 */
public abstract class Pool<T> implements Closeable {

    /**
     * @deprecated This will be private in future.
     */
    @Deprecated
    protected GenericObjectPool<T> internalPool;

    /**
     * Using this constructor means you have to set and initialize the internalPool yourself.
     *
     * @deprecated This constructor will be removed in future.
     */
    @Deprecated
    public Pool() {
    }


    /**
     * JedisPool extends JedisPoolAbstract extends Pool 构造方法
     */
    public Pool(final GenericObjectPoolConfig<T> poolConfig, PooledObjectFactory<T> factory) {
        initPool(poolConfig, factory);
    }

    @Override
    public void close() {
        destroy();
    }

    public boolean isClosed() {
        return this.internalPool.isClosed();
    }


    /**
     * 初始化pool连接池
     */
    @Deprecated
    public void initPool(final GenericObjectPoolConfig<T> poolConfig, PooledObjectFactory<T> factory) {

        if (this.internalPool != null) {
            try {
                closeInternalPool();
            } catch (Exception e) {
            }
        }

        this.internalPool = new GenericObjectPool<>(factory, poolConfig);
    }

    /**
     * This call only clears idle instances, not borrowed instances.
     */
    protected void clearInternalPool() {
        try {
            this.internalPool.clear();
        } catch (Exception e) {
            throw new JedisException("Could not clear the pool", e);
        }
    }




    /**
     * 从连接池中获取一个可用的 Redis 连接,然后使用该连接对象执行相应的命令。
     * <p>
     * 当连接被使用时，getResource() 方法会将连接标记为正在使用状态，并返回给调用者。如果连接池中的连接已经全部被占用，那么该方法会阻塞等待直到有可用的连接为止。
     * 当连接不再使用时，可以将其归还给连接池，以便其他线程或进程可以使用。这样可以确保连接池中的连接始终处于可用状态，并且能够有效地复用和管理。
     */
    public T getResource() {
        try {
            return internalPool.borrowObject();
        } catch (NoSuchElementException nse) {
            if (null == nse.getCause()) { // The exception was caused by an exhausted pool
                throw new JedisExhaustedPoolException(
                        "Could not get a resource since the pool is exhausted", nse);
            }
            // Otherwise, the exception was caused by the implemented activateObject() or ValidateObject()
            throw new JedisException("Could not get a resource from the pool", nse);
        } catch (Exception e) {
            throw new JedisConnectionException("Could not get a resource from the pool", e);
        }
    }

    /**
     * @param resource
     * @deprecated This will be removed in next major release. Use {@link Pool#returnResource(java.lang.Object)}.
     */
    @Deprecated
    protected void returnResourceObject(final T resource) {
        try {
            internalPool.returnObject(resource);
        } catch (RuntimeException e) {
            throw new JedisException("Could not return the resource to the pool", e);
        }
    }

    public void returnBrokenResource(final T resource) {
        if (resource != null) {
            returnBrokenResourceObject(resource);
        }
    }

    public void returnResource(final T resource) {
        if (resource != null) {
            returnResourceObject(resource);
        }
    }

    public void destroy() {
        closeInternalPool();
    }

    /**
     * @param resource
     * @deprecated This will be removed in next major release. Use {@link Pool#returnBrokenResource(java.lang.Object)}.
     */
    @Deprecated
    protected void returnBrokenResourceObject(final T resource) {
        try {
            internalPool.invalidateObject(resource);
        } catch (Exception e) {
            throw new JedisException("Could not return the broken resource to the pool", e);
        }
    }

    /**
     * @deprecated This will be removed in next major release. Use {@link Pool#destroy()}.
     */
    @Deprecated
    protected void closeInternalPool() {
        try {
            internalPool.close();
        } catch (RuntimeException e) {
            throw new JedisException("Could not destroy the pool", e);
        }
    }

    /**
     * Returns the number of instances currently borrowed from this pool.
     *
     * @return The number of instances currently borrowed from this pool, -1 if
     * the pool is inactive.
     */
    public int getNumActive() {
        if (poolInactive()) {
            return -1;
        }

        return this.internalPool.getNumActive();
    }

    /**
     * Returns the number of instances currently idle in this pool.
     *
     * @return The number of instances currently idle in this pool, -1 if the
     * pool is inactive.
     */
    public int getNumIdle() {
        if (poolInactive()) {
            return -1;
        }

        return this.internalPool.getNumIdle();
    }

    /**
     * Returns an estimate of the number of threads currently blocked waiting for
     * a resource from this pool.
     *
     * @return The number of threads waiting, -1 if the pool is inactive.
     */
    public int getNumWaiters() {
        if (poolInactive()) {
            return -1;
        }

        return this.internalPool.getNumWaiters();
    }

    /**
     * Returns the mean waiting time spent by threads to obtain a resource from
     * this pool.
     *
     * @return The mean waiting time, in milliseconds, -1 if the pool is
     * inactive.
     */
    public long getMeanBorrowWaitTimeMillis() {
        if (poolInactive()) {
            return -1;
        }

        return this.internalPool.getMeanBorrowWaitTimeMillis();
    }

    /**
     * Returns the maximum waiting time spent by threads to obtain a resource
     * from this pool.
     *
     * @return The maximum waiting time, in milliseconds, -1 if the pool is
     * inactive.
     */
    public long getMaxBorrowWaitTimeMillis() {
        if (poolInactive()) {
            return -1;
        }

        return this.internalPool.getMaxBorrowWaitTimeMillis();
    }

    private boolean poolInactive() {
        return this.internalPool == null || this.internalPool.isClosed();
    }

    public void addObjects(int count) {
        try {
            for (int i = 0; i < count; i++) {
                this.internalPool.addObject();
            }
        } catch (Exception e) {
            throw new JedisException("Error trying to add idle objects", e);
        }
    }
}
